package com.he.hsdyc.config.mvc;

import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AllowOriginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("拦截器作用...");
        httpServletResponse.setHeader("Access-Control-Allow-Origin","*");
        if("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) {
            httpServletResponse.setStatus(HttpStatus.SC_NO_CONTENT);
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE, PUT，PATCH");//当判定为预检请求后，设定允许请求的方法
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, x-requested-with, Accept ,token"); //当判定为预检请求后，设定允许请求的头部类型
            httpServletResponse.addHeader("Access-Control-Max-Age", "2592000");
        }else {
            httpServletResponse.setHeader("Access-Control-Allow-Headers"," Origin, X-Requested-With, Content-Type, Accept, token");
            httpServletResponse.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE ,PATCH");
            httpServletResponse.setHeader("Access-Control-Allow-Origin","*");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
